package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FeaturestandardRestController")
public class FeaturestandardRestController extends CmiEmaController {

	/**
	 * Create a new Featurestandard entity
	 * 
	 */
	@RequestMapping(value = "/newFeaturestandard", method = RequestMethod.POST)
	@ResponseBody
	public Object newFeaturestandard(@RequestBody Featurestandard featurestandard) {
		featurestandardService.saveFeaturestandard(featurestandard);
		return JSONObject.parse(
				cmiPsonService.toJsonString(featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandard.getId()), 2));
	}

	@RequestMapping(value = "/restNewFeaturestandard", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFeaturestandard(@RequestBody String featurestandardJson) {
		Featurestandard featurestandard = new Gson().fromJson(featurestandardJson, Featurestandard.class);
		appendReferences(featurestandard);
		featurestandardService.saveFeaturestandard(featurestandard);
		return JSONObject.parse(
				cmiPsonService.toJsonString(featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandard.getId()), 2));
	}

	@RequestMapping(value = "/saveFeaturestandard", method = RequestMethod.PUT)
	@ResponseBody
	public Featurestandard saveFeaturestandard(@RequestBody Featurestandard featurestandard) {
		featurestandardService.saveFeaturestandard(featurestandard);
		return featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandard.getId());
	}

	@RequestMapping(value = "/restSaveFeaturestandard", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFeaturestandard(@RequestBody String featurestandardJson) {
		Featurestandard featurestandard = new Gson().fromJson(featurestandardJson, Featurestandard.class);
		appendReferences(featurestandard);
		CmiPsonService cmiPsonService = new CmiPsonService();
		featurestandardService.saveFeaturestandard(featurestandard);
		return JSONObject.parse(
				cmiPsonService.toJsonString(featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandard.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFeaturestandard/{featurestandardId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFeaturestandard(@PathVariable Integer featurestandardId) {
		Featurestandard featurestandard = featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId);
		featurestandardService.deleteFeaturestandard(featurestandard);
	}

	@RequestMapping(value = "/restConfirmDeleteFeaturestandards")
	@ResponseBody
	public Object restConfirmDeleteFeaturestandards(@RequestBody Set<Integer> deleteFeaturestandardsIds) {
		Set<Featurestandard> deleteFeaturestandards = featurestandardDAO
				.findFeaturestandardsByIds(deleteFeaturestandardsIds);
		Set<Featurestandard> referencedFeaturestandards = featurestandardService
				.loadReferenceFeaturestandards(deleteFeaturestandards);
		deleteFeaturestandards.removeAll(referencedFeaturestandards);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFeaturestandards);
		jsonObject.put("deleteEntitys", deleteFeaturestandards);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFeaturestandards")
	@ResponseBody
	public Object restDeleteFeaturestandards(@RequestBody Set<Featurestandard> deleteFeaturestandards) {
		Iterator<Featurestandard> iterator = deleteFeaturestandards.iterator();
		while (iterator.hasNext()) {
			Featurestandard currentFeaturestandard = iterator.next();
			featurestandardService.deleteFeaturestandard(currentFeaturestandard);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFeaturestandards");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFeaturestandard/{featurestandardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeaturestandard(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeaturestandardFeature/{featurestandardId}/feature", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeaturestandardFeature(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId).getFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeaturestandardStandard/{featurestandardId}/standard", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeaturestandardStandard(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId).getStandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFeaturestandardUnit/{featurestandardId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFeaturestandardUnit(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId).getUnit(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Featurestandard featurestandard) {

		Feature feature = featurestandard.getFeature();
		if (feature != null)
			featurestandard.setFeature(featureService.findFeatureByPrimaryKey(feature.getId()));

		Standard standard = featurestandard.getStandard();
		if (standard != null)
			featurestandard.setStandard(standardService.findStandardByPrimaryKey(standard.getId()));

		Unit unit = featurestandard.getUnit();
		if (unit != null)
			featurestandard.setUnit(unitService.findUnitByPrimaryKey(unit.getId()));

	}

	@RequestMapping(value = "/restGetFeaturestandardFeature/{featurestandardId}/feature", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeaturestandardFeature(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId).getFeature(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFeaturestandardStandard/{featurestandardId}/standard", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeaturestandardStandard(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId).getStandard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFeaturestandardUnit/{featurestandardId}/unit", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFeaturestandardUnit(@PathVariable Integer featurestandardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				featurestandardDAO.findFeaturestandardByPrimaryKey(featurestandardId).getUnit(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFeaturestandards", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFeaturestandards() {
		return JSONObject.parse(cmiPsonService.toJsonString(featurestandardService.loadFeaturestandards(), 2));
	}

	@RequestMapping(value = "/restListFeaturestandardsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFeaturestandardsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = featurestandardPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Featurestandard> featurestandards = featurestandardDAO.findAllFeaturestandards(startResult,
				cmiPagination.getPaginationSize());
		String featurestandardString = cmiPsonService.toPsonString(featurestandards, 2, cmiPagination);

		return JSONObject.parse(featurestandardString);
	}

	@RequestMapping("/featurestandardSelectBox")
	@ResponseBody
	public JSONObject featurestandardSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Feature":
				entitySet = featureService.loadFeaturesByIdSet(searchValue);
				break;
			case "Standard":
				entitySet = standardService.loadStandardsByIdSet(searchValue);
				break;
			case "Unit":
				entitySet = unitService.loadUnitsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Feature":
				entitySet = featureDAO.findAllFeatures((pageNumber - 1) * paginationSize, paginationSize);
				count = featureService.countFeatures();
				break;
			case "Standard":
				entitySet = standardDAO.findAllStandards((pageNumber - 1) * paginationSize, paginationSize);
				count = standardService.countStandards();
				break;
			case "Unit":
				entitySet = unitDAO.findAllUnits((pageNumber - 1) * paginationSize, paginationSize);
				count = unitService.countUnits();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Feature":
				entitySet = featureDAO.findFeatureByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = featureService.countFeaturesByName(queryword);
				break;
			case "Standard":
				entitySet = standardDAO.findStandardByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = standardService.countStandardsByName(queryword);
				break;
			case "Unit":
				entitySet = unitDAO.findUnitByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = unitService.countUnitsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
